package rdf;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryParseException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;

/**
 * Servlet implementation class SemanticQueryServlet
 */
@WebServlet("/SemanticQueryServlet/*")
public class SemanticQueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private static Model model;
	private static final String FILE_NAME_RDF = "OntologyHockey_0627596.rdf";
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SemanticQueryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		// create an empty model
		model = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(FILE_NAME_RDF);
		if (in == null) {
			throw new IllegalArgumentException("File: " + FILE_NAME_RDF
					+ " not found");
		}

		// read the RDF/XML file
		model.read(in, null);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Writer w = response.getWriter();

		w.write("<html><body>");
		w.write("<h1>SPARQL Endpoint</h1>");
		w.write("<form action='' method='post'>");
		w.write("<textarea rows='18' cols='80' name='query' id='query' >");
		w.write("SELECT ?subject ?object WHERE { ?subject owl:sameAs ?object}");
		w.write("</textarea> <br/>");
		w.write("<input type='submit' value='Run' >");
		w.write("</form>");
		w.write("<a href='/RDF_Browser/SemanticServlet/'>Semantic Browser</a> <br>");
		w.write("</html></body>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String queryPrefix = "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
			+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
			+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
			+ "PREFIX hy:<http://www.semanticweb.org/ontologies/2011/11/OntologyHockey_0627596.owl#> " 
			+ "PREFIX owl:<http://www.w3.org/2002/07/owl#> ";
		
		Writer w = response.getWriter();
		w.write("<html><body>");
		try
		{
			QueryExecution qe = QueryExecutionFactory.create(queryPrefix + request.getParameter("query"), model);
			ResultSet results = qe.execSelect();
				
			List<String> vars = qe.getQuery().getResultVars();
			
			w.write("<table border='1'>");
			w.write("<tr>");
			for(String var : vars)
			{
				w.write("<th>" + var + "</th>");
			}
			w.write("</tr>");
			
			while (results.hasNext()) {
				QuerySolution result = results.nextSolution();
				
				w.write("</tr>");
				for(String var : vars)
				{
					w.write("<td>" + result.get(var) + "</td>");
				}
				w.write("<tr>");
			}
			
			w.write("</table>");
			w.write("<br/> <a href='/RDF_Browser/SemanticQueryServlet/'>Back</a> <br/>");
			w.write("<a href='/RDF_Browser/SemanticServlet/'>Semantic Browser</a> <br/>");
			
			qe.close();
		}
		catch(QueryParseException qpe)
		{
			w.write(qpe.getMessage());
		}
		
		
		//List<PropertyObject> objectProperties = getIndirectProperties(results, "rdfs", "hasSubClass");
		
		w.write("</html></body>");
	}
	

}
